<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use App\Models\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Request;
use App\Models\App;

class Cate extends Model
{
	use AdminBuilder, ModelTree ;
	protected $casts = ['sets'=>'json','extend' => 'json'];  
	protected $app_name;
	protected $table = 'cates';
    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $app=[])
    {
        if($app && is_string($app[0]) && count($app)===1){
			$this->app_name = $app_name = $app[0];
			static::addGlobalScope('avaiable',function(Builder $builder) use($app_name){
				$builder->where('app_name',$app_name);
			});
			parent::__construct();
		}else{
			parent::__construct($app);
		}
    }


    protected static function boot() {    
        parent::boot();
        static::saved(function($model) {
			$model->removeCache();
        });

        static::deleted(function ($model) {
			$model->removeCache();
        });
    }


	public function getGroupsAttribute($value){
		if(!empty($value)){
			$value = str2arr($value);
		}else{
			$value = [];
		}
		return $value;
	}


    /**
     * determine if enable menu bind permission.
     *
     * @return bool
     */

 
    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }


	public function app()
	{
		return $this->belongsTo(App::class, 'app_name','name');
	}

	public function removeCache()
    {
		if(empty($this->app_name)){
			/*
			$apps = get_app();
			foreach($apps as $k=>$v){
				\Cache::forget('sys_table_cates_'.$k);
			}*/
		}else{
			\Cache::forget('sys_table_cates_'.$this->app_name);
		}
    }

}
